package client

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//TODO:要做缓存
//抽奖的奖品列表
func ListLotteryProduct(multiOrm ...orm.Ormer) ([]LotteryProduct, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			status = 1
		`, TableLotteryProduct)
	o := NewOrm(multiOrm, DBChess)
	var gl []LotteryProduct
	_, err := o.Raw(sql).QueryRows(&gl)
	return gl, err
}

//TODO:要做缓存
//钻石兑换抽奖次数列表
func ListLotteryExchange(multiOrm ...orm.Ormer) ([]LotteryExchange, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		`, TableLotteryExchange)
	o := NewOrm(multiOrm, DBChess)
	var gl []LotteryExchange
	_, err := o.Raw(sql).QueryRows(&gl)
	return gl, err
}

//返回玩家获取的奖品列表
func ListLotteryUser(uid int64, multiOrm ...orm.Ormer) ([]LotteryUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			uid = %v
		`, TableLotteryUser, uid)
	o := NewOrm(multiOrm, DBChess)
	var gl []LotteryUser
	_, err := o.Raw(sql).QueryRows(&gl)
	return gl, err
}

//更新用户的抽奖次数
func UpdateLotteryCount(uid, lotteryCount int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	sql := fmt.Sprintf(`UPDATE %v SET lottery_count = lottery_count + %v
			WHERE uid = %v AND (lottery_count +%v) >=0`,
		TableClientUserAttr, lotteryCount, uid, lotteryCount)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//

//写用户用钻石购买抽奖次数的记录
func NewLotteryConsumeRecord(uid, diamond, lotteryCount int64, multiOrm ...orm.Ormer) (int64, error) {
	data := map[string]interface{}{
		"uid":           uid,
		"diamond":       diamond,
		"lottery_count": lotteryCount,
		"create_time":   time.Now().Unix(),
	}
	o := NewOrm(multiOrm, DBChess)
	values, sql := InsertSql(TableLotteryConsumeRecord, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}
